package mypassForStu.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import mypassForStu.common.R;
import mypassForStu.entity.Apply;
import mypassForStu.entity.Student;
import mypassForStu.service.ApplyService;
import mypassForStu.tools.CreateTable;
import mypassForStu.tools.IDUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.time.LocalDateTime;
import java.util.Base64;
import java.util.List;

@RestController
@RequestMapping("/apply")
public class ApplyController {

    @Autowired
    ApplyService applyService;

    //提交申请
    @PostMapping("/submit")
    public R<Apply> submit(@RequestBody Apply apply){
        String Id = IDUtils.getId();
        apply.setApplyId(Id);
        apply.setStat(0);
        applyService.save(apply);
        return R.success(apply);
    }

    //获取申请
    @PostMapping("/get")
    public R<Apply> get(@RequestBody Student student){
        LambdaQueryWrapper<Apply> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Apply::getStudentId, student.getStudentId());
        List<Apply> applies = applyService.list(queryWrapper);
        LocalDateTime time = LocalDateTime.now();
        for(Apply apply: applies){
            if(apply.getStat()!=3){
                if(time.isAfter(apply.getBackTime())){
                    apply.setStat(2);
                    apply.setRecom("已超时！");
                    applyService.updateById(apply);
                }
                return R.success(apply);
            }
        }
        return R.success(null);
    }

    @PostMapping("/repeal")
    public R<String> repeal(@RequestBody Apply apply){
        if(apply == null){
            return R.error("撤销失败");
        }
        applyService.removeById(apply.getApplyId());
        return R.success("撤销成功");
    }

    @PostMapping("/backSchool")
    public R<String> backSchool(@RequestBody Apply apply){
        apply = applyService.getById(apply.getApplyId());
        if(apply.getStat() == 1){
            apply.setStat(3);
            applyService.updateById(apply);
        }
        return R.success("已返校");
    }

    @PostMapping("/getImg")
    public R<String> getJpg(@RequestBody Apply apply) throws IOException {
        apply = applyService.getById(apply.getApplyId());
        if(apply.getStat() == 1){
            String fileName = CreateTable.createTable(apply);
            BufferedImage bufferedImage = ImageIO.read(new FileInputStream(new File(fileName)));
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, "PNG", out);
            String data = Base64.getEncoder().encodeToString(out.toByteArray());
            return R.success(data);
        }
        else {
            return R.error("未审批通过");
        }
    }
}
